package service

import (
	"goseckill/dao"
	"goseckill/models"

	"golang.org/x/crypto/bcrypt"
)

// 定义服务接口
type IUserService interface {
	IsPwdSuccess(userName string, pwd string) (user *models.User, isOk bool)
	AddUser(user *models.User) (userId int64, err error)
}

// ServiceImpl
type UserService struct{
	// Service 对一个或多个DAO的封装
	UserDao dao.IUserDao
}
func NewUserService(dao dao.IUserDao) IUserService {
	return &UserService{dao}
}


// 验证密码
func (u *UserService) IsPwdSuccess(userName string, pwd string) (user *models.User, isOk bool) {
	// 首先到数据库中查询数据
	user,err := u.UserDao.Select(userName)
	if err!=nil {
		return 
	}
	// 对比密码  数据库中的密码是经过哈希计算的
	// 所以，这里需要对哈希密码进行对比
	isOk,_ = validatePasswd(pwd, user.HashPassword)
	if !isOk {
		return &models.User{},false
	}
	return 
}

func (u *UserService) AddUser(user *models.User)(userID int64, err error) {
	// 对原始密码加密
	pwd,err := generatePasswd(user.HashPassword)
	if err!=nil {
		return userID,err
	}
	user.HashPassword = string(pwd)
	// 插入
	return u.UserDao.Insert(user)
}

func generatePasswd(userPasswd string) ([]byte,error) {
	return bcrypt.GenerateFromPassword([]byte(userPasswd),bcrypt.DefaultCost)
}
func validatePasswd(userPasswd string, hashPasswd string) (isOK bool,err error) {
	if err = bcrypt.CompareHashAndPassword([]byte(hashPasswd), []byte(userPasswd));err!=nil{
		return false,err
	}
	return true,nil
}